<template>
  <div class="container">
    <div class="app-container">
      <el-card shadow="never">
        <el-container>
          <el-header>试题录入</el-header>
        </el-container>
        <el-divider></el-divider>
        <div class="formBox">
          <el-form
            ref="formDate"
            :model="form"
            :rules="rules"
            :label-position="(labelPosition = 'left')"
            label-width="100px"
          >
            <el-form-item label="学科：" prop="subjectID">
              <el-select
                v-model="form.subjectID"
                placeholder="请选择"
                @focus="getSubjectID"
              >
                <el-option
                  v-for="item in subjectNameList"
                  :key="item.id"
                  :label="item.subjectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录：" prop="catalogID">
              <el-select
                v-model="form.catalogID"
                placeholder="请选择"
                @focus="getDirectoryList"
              >
                <el-option
                  v-for="item in directoryList"
                  :key="item.id"
                  :label="item.directoryName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业：" prop="enterpriseID">
              <el-select
                placeholder="请选择"
                v-model="form.enterpriseID"
                @focus="getCompanysList"
              >
                <el-option
                  v-for="item in companysList"
                  :key="item.id"
                  :label="item.company"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市：" required>
              <el-col :span="5">
                <el-form-item prop="province">
                  <el-select
                    placeholder="请选择"
                    v-model="form.province"
                    @change="provinceChange(form.province)"
                  >
                    <el-option
                      v-for="(item, index) in provinces"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="city">
                  <el-select placeholder="请选择" v-model="form.city">
                    <el-option
                      v-for="(item, index) in cities"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="方向：" prop="direction">
              <el-select placeholder="请选择" v-model="form.direction">
                <el-option
                  v-for="(item, index) in direction"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题型：" prop="questionType">
              <el-radio-group v-model="form.questionType">
                <el-radio
                  v-for="item in questionType"
                  :key="item.value"
                  :label="item.value + ''"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度：" prop="difficulty">
              <el-radio-group v-model="form.difficulty">
                <el-radio
                  v-for="item in difficulty"
                  :key="item.value"
                  :label="item.value + ''"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干：" prop="question">
              <vue-editor
                placeholder="请输入题干"
                v-model="form.question"
                style="width: 70%"
              ></vue-editor>
            </el-form-item>
            <el-form-item label="选项：" v-if="form.questionType === '1'">
              <el-radio-group v-model="radioValue" class="eRg">
                <el-radio
                  v-for="(item, index) in form.options"
                  :key="item.code"
                  :label="item.code"
                  style="display: block; padding-top: 20px"
                >
                  <span>{{ item.code }}：</span>
                  <el-input
                    class="ergInput"
                    v-model="item.title"
                    placeholder="请输入选项内容"
                    style="margin-right: 5px; width: 420px"
                  />
                  <UploadImage
                    ref="StaffPhoto"
                    class="uploadImge"
                  ></UploadImage>
                  <span
                    v-if="checkCloseBtn"
                    style="transform: translateX(20px); color: red"
                    class="el-icon-circle-close"
                    @click.stop="delCheck(index)"
                  ></span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选项：" v-if="form.questionType === '2'">
              <el-checkbox-group v-model="checkList">
                <el-checkbox
                  v-for="(item, index) in form.options"
                  :key="item.code"
                  :label="item.code"
                  style="display: block; padding-top: 20px"
                  class="checked"
                >
                  <span>{{ item.code }}：</span>
                  <el-input
                    placeholder="请输入选项内容"
                    v-model="item.title"
                    style="margin-right: 5px; width: 420px"
                  />
                  <UploadImage
                    ref="StaffPhoto"
                    class="uploadImge"
                  >
                    <span @click="getComponentOrder(index)"></span>
                  </UploadImage>
                  <span
                    v-if="checkCloseBtn"
                    style="transform: translateX(20px); color: red"
                    class="el-icon-circle-close"
                    @click.stop="delCheck(index)"
                  ></span>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="">
              <el-button
                :disabled="form.questionType !== '2'"
                v-if="form.questionType !== '3'"
                type="primary"
                size="small"
                @click="addCheckbox"
                >增加选项与答案</el-button
              >
              <el-button
                v-if="form.questionType !== '3'"
                @click="checkCloseBtn = !checkCloseBtn"
                type="danger"
                size="small"
              >
                删除选项与答案
              </el-button>
            </el-form-item>
            <el-form-item label="解析视频：">
              <el-input
                v-model="form.videoURL"
                type="text"
                style="width: 70%"
              ></el-input>
            </el-form-item>
            <el-form-item label="答案解析：" prop="answer">
              <vue-editor
                placeholder="请输入解析内容"
                v-model="form.answer"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item label="题目备注：">
              <el-input
                v-model="form.remarks"
                type="textarea"
                style="width: 70%"
              ></el-input>
            </el-form-item>
            <el-form-item label="试题标签：">
              <el-select
                placeholder="请选择"
                v-model="form.tags"
                @focus="getsimpleList"
              >
                <el-option
                  v-for="item in simpleList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value + ''"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <el-row type="flex" justify="left" style="margin-left: 80px">
          <el-col :span="6">
            <el-button type="primary" size="medium" @click="confirmBtn"
              >确认提交</el-button
            >
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor'
import { list } from '@/api/hmmm/subjects.js'
import { list as directoryList } from '@/api/hmmm/directorys.js'
import { list as companysList } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { tagSimple } from '@/api/hmmm/tags'
import { add, update, detail } from '@/api/hmmm/questions'
import UploadImage from '../components/upload-image.vue'
export default {
  props: {
    editForm: {
      type: Object
    }
  },
  components: {
    VueEditor,
    UploadImage
  },
  data () {
    return {
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: 1 + '', // 题型
        difficulty: 1 + '', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: !!0 },
          { code: 'B', title: '', img: '', isRight: !!0 },
          { code: 'C', title: '', img: '', isRight: !!0 },
          { code: 'D', title: '', img: '', isRight: !!0 }
        ], // 选项(对象数组)code, title, img, isRight
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [
          { required: true, message: '学科不能为空', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '目录不能为空', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '企业名称不能为空', trigger: ['blur', 'change'] }
        ],
        province: [
          { required: true, message: '城市不能为空', trigger: ['blur', 'change'] }
        ],
        direction: [
          { required: true, message: '业务不能为空', trigger: ['blur', 'change'] }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: ['blur', 'change'] }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '题干不能为空', trigger: ['blur', 'change'] }
        ],
        answer: [
          { required: true, message: '答案解析不能为空', trigger: ['blur', 'change'] }
        ]
      },
      radioValue: '',
      checkList: [],
      subjectNameList: [], // 学科列表
      directoryList: [], // 目录列表
      companysList: [], // 企业列表
      provinces: [], // 城市
      cities: [], // 地区
      simpleList: [], // 标签
      direction, // 方向
      questionType, // 题型
      difficulty, // 难度
      checkCloseBtn: false
    }
  },
  created () {
    // this.getSubjectID()
    // this.getDirectoryList()
    // this.getCompanysList()
    this.getProvince()
    // this.getsimpleList()
    this.getsimpleList()
    this.getFormData()
  },
  methods: {
    getProvince () { // 城市列表
      this.provinces = provinces()
    },
    provinceChange (province) { // 地区列表
      this.cities = citys(province)
    },
    async getSubjectID () { // 学科列表
      const { data } = await list()
      this.subjectNameList = data.items
    },
    async  getDirectoryList () { // 目录列表
      const { data } = await directoryList()
      this.directoryList = data.items
    },
    async  getCompanysList () { // 企业列表
      const { data } = await companysList()
      this.companysList = data.items
    },
    async getsimpleList () { // 标签列表
      const { data } = await tagSimple()
      this.simpleList = data
    },
    addCheckbox () { // 增加选项与答案
      var option = String.fromCharCode('A'.charCodeAt(0) + this.form.options.length) // 字母自增
      this.form.options.push({ code: option, title: '', img: '', isRight: 0 })
    },
    async detail () {
      const data = await detail()
      this.form = data
    },
    delCheck (index) { // 删除当前选项
      const CHARCODE_A_UC = 65
      const option = new Array(26).fill(null).map((v, i) => String.fromCharCode(CHARCODE_A_UC + i)) // 获取26个字母
      if (this.form.options.length <= 4) {
        return this.$message.warning('禁止删除')
      } else {
        this.form.options.forEach(async (item, i) => {
          if (i === index) {
            await this.$confirm('确定要删除吗')
            this.form.options.splice(i, 1)
            this.form.options.forEach((obj, ind) => { // 删除之后让后面的元素进行填补
              obj.code = option[ind]
            })
          }
        })
      }
    },
    confirmBtn () { // 提交表单
      this.$refs.formDate.validate(async (isOk) => {
        if (isOk) {
          // 图片地址数组转换
          const url = this.$refs.StaffPhoto.map(list => list.fileList.map(img => img.url)).map(item => item.toString())
          // this.form.questionType === '1' && this.form.options.forEach((item, index) => { item.code === this.radioValue && (item.isRight = !!1) })
          if (this.form.questionType === '1') { // 改变单选 正确选项 以及图片地址
            this.form.options.forEach((item, index) => {
              item.img = url[index]
              if (item.code === this.radioValue) {
                item.isRight = !!1
              }
            })
          }
          // this.form.questionType === '2' && this.form.options.forEach(item => { this.checkList.forEach(check => { check === item.code && (item.isRight = !!1) }) })
          if (this.form.questionType === '2') { // 多选正确选项 以及图片地址
            this.form.options.forEach((item, index) => {
              item.img = url[index]
              this.checkList.forEach(check => {
                if (check === item.code) {
                  item.isRight = !!1
                }
              })
            })
          }
          this.form.questionType === '3' && (this.formData.options = [])

          if (this.form.id) { // 编辑
            await update(this.form)
            console.log(this.form)
            this.$message.success('更新成功')
          } else {
            await add(this.form)
            this.$message.success('添加成功')
            this.$router.push('/questions/list')
          }
        } else {
          return false
        }
        this.$refs.formDate.resetFields()
      })
    },
    // 获取基础题库表单回填数据
    async getFormData () {
      if (!this.$route.query.id) return
      const { data } = await detail({ id: this.$route.query.id })
      // 图片地址数组转换
      const fileList = this.$refs.StaffPhoto.map(list => list.fileList)
      data.options.forEach((item, index) => {
        if (data.questionType === '1') { // 判断单选
          if (item.isRight === 0) {
            item.isRight = false
          } else if (item.isRight === 1) { // 判断多选
            item.isRight = true
            item.code = this.radioValue
          }
        } if (data.questionType === '2') {
          if (item.isRight === 0) {
            item.isRight = false
          } else if (item.isRight === 1) {
            item.isRight = true
            this.checkList.push(item.code)
          }
        }
        if (item.img) {
          fileList[index].push({ url: item.img })
          console.log(fileList[index])
        }
      })
      this.form = data
      console.log(fileList)
    },
    getComponentOrder (index) {
      console.log(123)
    }
  }
}
</script>

<style scoped lang='scss'>
.el-header {
  background: linear-gradient(to right, #1493fa, #01c6fa);
  color: #fff;
  text-align: left;
  line-height: 60px;
  font-weight: 700;
}
.formBox {
  margin-left: 80px;
}
.uploadImge {
  display: inline-block;
  vertical-align: middle;
  text-align: center;
  // width: 80px;
  // height: 50px;
  line-height: 1;
}
.eRg :last-child .el-radio__label .ergInput {
  width: 92.5%;
}
</style>
